package com.uxsino.simo.indicator.retractor;

import com.uxsino.commons.utils.config.PropElement;
import com.uxsino.simo.indicator.Indicator;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;
import com.uxsino.simo.utils.ConfigLoadingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

public class TomcatOSInfoRetractor extends CompoundValueRetractor {
    private static Logger logger = LoggerFactory.getLogger(TomcatOSInfoRetractor.class);

    private Map<String, String> fieldKeyNameMap = new HashMap<>(fieldRetrievers.size());

    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {
        if (obj == null) {
            logger.error("retract input is null");
            return null;
        }
        String str = (String) obj;
        str = str.replaceAll("\\s*|\r\n|\n\r\\s|\\n\\r|\\r|\\n", "");
        System.out.println(str);
        Map<String, Object> result = new HashMap<>(fieldRetrievers.size());
        Map<String, String> infoMap = new HashMap<>();
        for (Map.Entry<String, IValueRetractor> entry : fieldRetrievers.entrySet()) {
            String keyName = fieldKeyNameMap.get(entry.getKey());
            Object value = null;
            infoMap.put(keyName, str);
            if (null == keyName) {
                logger.error("key_name should not be null for {} ", entry.getKey());
                continue;
            }
            if (infoMap.containsKey(keyName)) {
                value = entry.getValue().retract(entity, ctxt, qt, infoMap.get(keyName));
            } else {
                logger.error("cannot get info of {}", entry.getKey());
            }
            result.put(entry.getKey(), value);
            infoMap.clear();
        }
        return result;
    }

    public void addFieldKeyName(String fieldName, String keyName) {
        fieldKeyNameMap.put(fieldName, keyName);
    }

    @Override
    public void loadProp(Indicator ind, PropElement eRetractor, ConfigLoadingContext lctxt) {
        super.loadProp(ind, eRetractor, lctxt);
        for (PropElement eFld : eRetractor.getElements("field")) {
            String fieldName = eFld.getProp("name", "");
            String keyName = eFld.getProp("key_name", "");

            if (keyName.isEmpty()) {
                keyName = fieldName;
            }
            addFieldKeyName(fieldName, keyName);
        }
    }
}
